package com.mdnote.practice;

import org.junit.Assert;
import org.junit.Test;

import java.util.LinkedList;

/**
 * @author Rhythm-2019
 * @version 1.0
 * @date 2020/11/15 9:37
 * @Email rhythm_2019@163.com
 * @Description  402. 移掉K位数字
 */
public class LeetCode402 {


    public String removeKdigits(String num, int k) {
        LinkedList<Character> dueue = new LinkedList<>();

        for (int i = 0; i < num.length(); i++) {
            while (k > 0 && !dueue.isEmpty() && dueue.peekLast() > num.charAt(i)) {
                dueue.pollLast();
                k--;
            }
            dueue.offerLast(num.charAt(i));
        }

        for (int i = 0; i < k; i++) {
            dueue.pollLast();
        }


        StringBuilder stringBuilder = new StringBuilder();
        boolean skipZero = true;
        while (!dueue.isEmpty()) {
            Character c = dueue.pollFirst();
            if (c == '0' && skipZero) {
                continue;
            }
            skipZero = false;
            stringBuilder.append(c);
        }

        return "".equals(stringBuilder.toString()) ? "0" : stringBuilder.toString();
    }

    @Test
    public void test_01() {
        LeetCode402 leetCode402 = new LeetCode402();
        Assert.assertEquals(leetCode402.removeKdigits("1432219", 3), "1219");
        Assert.assertEquals(leetCode402.removeKdigits("10", 1), "0");
    }
}
